package com.alinesno.cloud.initializr.starter.cicd.deploy.k8s.api;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alinesno.cloud.initializr.starter.cicd.deploy.k8s.BaseApi;
import com.alinesno.cloud.initializr.starter.cicd.deploy.k8s.bean.IngressBean;

import io.fabric8.kubernetes.api.model.IntOrString;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.extensions.Ingress;
import io.fabric8.kubernetes.api.model.extensions.IngressBackend;
import io.fabric8.kubernetes.api.model.extensions.IngressRule;
import io.fabric8.kubernetes.api.model.extensions.IngressSpec;
import io.fabric8.kubernetes.api.model.extensions.IngressStatus;

/**
 * 操作域名 
 * 
 * @author WeiXiaoJin
 * @date 2021年6月25日 下午9:33:55
 */
@Component
public class IngressApi extends BaseApi {

	private static final Logger log = LoggerFactory.getLogger(IngressApi.class) ; 
	
	/**
	 * 创建一个域名 
	 * @param bean
	 * @return 
	 */
	public Ingress createIngress(IngressBean bean) {
		Ingress item = new Ingress() ; 
		
		IngressStatus status = new IngressStatus() ; 
		status.setLoadBalancer(null);
	
		IngressBackend backend = new IngressBackend() ; 
		backend.setServiceName(bean.getServiceName());
		
		IntOrString port = new IntOrString() ; 
		port.setIntVal(bean.getServicePort());
		backend.setServicePort(port);
		
		List<IngressRule> rules = new ArrayList<IngressRule> () ; 
		
		IngressRule ingressRule = new IngressRule() ; 
		ingressRule.setHost(bean.getDomain()) ; 
		rules.add(ingressRule) ; 
		
		IngressSpec spec = new IngressSpec() ; 
		spec.setRules(rules);
		spec.setBackend(backend);
		
		item.setApiVersion(bean.getApiVersion()) ; 
		item.setKind("Ingress");
		item.setSpec(spec);
		item.setStatus(status);
		
		ObjectMeta metadata = new ObjectMeta() ; 
		metadata.setAdditionalProperty("name" ,  bean.getIngressName()) ; 
//		metadata.setAdditionalProperty("namespace" ,  bean.getNamespace()) ; 
		item.setMetadata(metadata);
		
		Ingress ingress = client().extensions().ingresses().inNamespace(bean.getNamespace()).create(item) ; 
		log.debug("create ingress = {}" , ingress) ; 
		
		return ingress ; 
	}
	
}
